

//
//  RJCheckVC.m
//  AirQuality
//
//  Created by Po on 15/3/10.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCheckVC.h"
#import "RJCheckProvinceModel.h"

#import "RJStatusTable.h"
#import "RJCheckSendVC.h"
#import "RJOutCityView.h"
#import "RJHomeTopSectionView.h"
#import "RJCheckBottomView.h"
#import "RJCheckDataVC.h"
#import "RJLineView.h"
#import "CheckBottomSectionView.h"
#import "RJCheckExplainView.h"
#import "RJCheckSendModel.h"

#import "RJLoadView.h"

#define downHeight 30
@interface RJCheckVC ()
                        <
                        RJOutCityViewDelegate,
                        RJHomeTopSectionViewDelegate,
                        RJCheckBottomViewDelegate,
                        RJMainSuperDelegate,
                        RJMainSuperDelegate,
                        RJStatusTableCellDelegate,
                        CheckBottomSectionDelegate
                        >

@property (retain, nonatomic) RJStatusTable * statusView;                   //状态表
@property (retain, nonatomic) RJCheckSendVC * sendCheckVC;                  //提交审核
@property (retain, nonatomic) RJLineView * lineView;                        //折线图
@property (retain, nonatomic) RJOutCityView * cityTable;                    //城市选择
@property (retain, nonatomic) UIView * cityTableView;                       //城市选择背景层
@property (retain, nonatomic) RJHomeTopSectionView * typeView;              //空气质量类型列表
@property (retain, nonatomic) RJHomeTopSectionView * cityTypeView;              //空气质量类型列表
@property (retain, nonatomic) RJCheckBottomView * bottomView;               //下方详情视图
@property (retain, nonatomic) CheckBottomSectionView * sectionView;         //选项栏
@property (retain, nonatomic) RJCheckExplainView * explainView;             //图例图
@property (retain, nonatomic) UIButton * explainButton;                     //示例图片

@property (strong, nonatomic) RJCheckSendModel     * sendModel;
@property (retain, nonatomic) RJCheckProvinceModel * model;                 //数据模型
@property (assign, nonatomic) NetRequestStatus lineNetRequest;              //折线图数据请求状态
@property (assign, nonatomic) NetRequestStatus stationsNetRequest;          //站点数据请求状态
@property (assign, nonatomic) NSUInteger currentCityCount;                   //当前城市
@property (assign, nonatomic) BOOL isSelectAnim;                            //显示选择
@property (assign, nonatomic) BOOL isNetFail;                               //网络失败动画
@property (assign, nonatomic) BOOL isRun;                                   //正在运行
@property (strong, nonatomic) NSString * pollutants;                       //污染物
@property (strong, nonatomic) UIButton * currentButton;                     // 当前选项
@property (strong, nonatomic) UIView * twoTopLine ;                      //城市农村选项
@property (strong, nonatomic) NSMutableArray *allCityCode;                     //所有城市站点
@property (strong, nonatomic) NSMutableDictionary * allStationData;            //   所有站点数据
@property (assign, nonatomic) BOOL stationType;
@property (strong, nonatomic) UIView * twoTopSectionView;   //上方站点选择
@property (retain, nonatomic) NSString * stationCodeString;// 站点拼接字符串
@property (strong, nonatomic) NSNumber * cityCode;
@property (strong, nonatomic) NSMutableArray *allStationCode;
@property (strong, nonatomic) NSMutableArray * colorArray;
@property (strong, nonatomic) NSArray * timeArray;
@property (strong, nonatomic) NSDictionary * checkDic;

- (void)initData;
- (void)initInterface;
- (void)initNet;

@end

@implementation RJCheckVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initData];
        [self initInterface];
        [self initNet];
    }
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
 
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ShowType" object:nil];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
}
#pragma mark - user-defined initialization function
- (void)initData
{
    _isRun = YES;
    _isNetFail = NO;
    _isSelectAnim = NO;
    _currentCityCount = 0;
    _lineNetRequest = NetRequestStatusDoing;
    _stationsNetRequest = NetRequestStatusDoing;
    _allStationCode = [NSMutableArray array];
    _allCityCode = [NSMutableArray array];
    _colorArray = [NSMutableArray array];
    _model = [[RJCheckProvinceModel alloc] init];
//    [_model getCity24ValueWithCityCode:[RJUserData defaultRJUserData].currentCityCode];
    [self setDelegate:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didGetCity24Value:) name:@"checkDidGetCity24Value" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendCheckProplemData:) name:@"sendCheckProplemData" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showType) name:@"ShowType" object:nil];
}

- (void)initInterface
{
//    [self getTwoTopSectionView];
    [self.view addSubview:[self getCityTable]];
    if (![RJUserData defaultRJUserData].isProvince) {
        [self.mainView addSubview:[self getTypeView:CGRectMake(0, CGRectGetHeight(self.mainView.frame) / 2, ScreenWidth , 40)]];
        CGFloat _typeMaxY = CGRectGetMaxY(_typeView.frame) + 5;
        CGRect bottomRect = CGRectMake(0, _typeMaxY, ScreenWidth, CGRectGetHeight(self.mainView.frame) - _typeMaxY - 5);
        [self.mainView addSubview:[self getCheckBottomView:bottomRect]];
        CGRect lineRect = CGRectMake(0, 0, ScreenWidth, CGRectGetHeight(self.mainView.frame) / 2 - 5);
        [self.mainView addSubview:[self getLineViewWithData:nil frame:lineRect]];
        CGRect rect = CGRectMake(0, lineRect.origin.y + lineRect.size.height - 40, 40, 40);
        [self.view addSubview:[self getExplainButton:rect]];
    
        //选取器
        CGRect typeRect = CGRectMake(0, CGRectGetHeight(self.mainView.frame) / 2, ScreenWidth , 40);
        [self.mainView addSubview:[self getTypeView:typeRect]];
        //类型
        CGRect sectionRect = CGRectMake(0, CGRectGetHeight(self.mainView.frame) / 2, ScreenWidth , 40);
        [self.mainView addSubview:[self getSectionView:sectionRect]];
        
        //图例
        CGFloat explainY = sectionRect.origin.y;
        CGRect explainRect = CGRectMake(-ScreenWidth,
                                        explainY,
                                        ScreenWidth,
                                        ScreenHeight - sysTabbarHeight - explainY);
        [self.mainView addSubview:[self getExplainView:explainRect]];
            }
    if ([RJUserData defaultRJUserData].isProvince) {
        [self.navBar.rightButton removeFromSuperview];
//        [self.navBar.rightButton setTitle:@"下发" forState:UIControlStateNormal];
//        [self.navBar.rightButton addTarget: self action:@selector(sendMessageToCity) forControlEvents:UIControlEventTouchUpInside];
    }
    [self.navBar.returnButton removeTarget:nil action:@selector(popViewControllerAnimated:) forControlEvents:UIControlEventTouchUpInside];
    if ([RJUserData defaultRJUserData].isProvince) {
        self.navBar.isOtherReturnButton = NO;
        [self.navBar setReturnButtonHidden:NO];
        self.navBar.rightButton.titleLabel.font = [UIFont systemFontOfSize:18];
        self.navBar.rightButton.frame = CGRectMake(ScreenWidth - 75, 11, 63, 30);
        [self.navBar.rightButton setImageEdgeInsets:UIEdgeInsetsMake(15, 15, 15, 45)];
        self.navBar.rightButton.layer.borderWidth = 2;
        self.navBar.rightButton.layer.borderColor = GetRGBColor(27, 170, 169, 1).CGColor;
        self.navBar.rightButton.layer.cornerRadius = 5;
//        self.navBar.rightButton.center = self.navBar.center;
        [self.navBar.returnButton addTarget:self action:@selector(pressReturnButton:) forControlEvents:UIControlEventTouchUpInside];
        [self addChildViewController:[self getStatusTable]];
        [self.view addSubview:[self getStatusTable].view];
        
//        CGRect rect = [RJTools getReSizeRect:self.navBar.returnButton.frame size:-5];
//        [self.navBar.returnButton setFrame:rect];
//        self.navBar.rightButton.frame = CGRectMake(ScreenWidth-60, 0, 60, 60);
    } else {
        [self addLoadView];
        [self getCheckSendVC];
    }
}

- (void)initNet
{
    [self netRequsetAllCityAndStation];
}

- (void)netRequsetAllCityAndStation
{
    
    [self addLoadView];
    _isNetFail = NO;
    NSUserDefaults * userId = [NSUserDefaults standardUserDefaults];
    NSArray * userIdArr = [userId objectForKey:@"userId1"];
    NSString * userId1 = userIdArr[0];
    NSString * userCityCode = userIdArr[1];
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].AllCityAndStation data:@{@"stationtype":@1,@"timepoint":[RJTools getTimeWithFormat:@"yyyy-MM-dd" time:YesterdayDate],@"userId":userId1,@"cityCode":userCityCode} completeBlock:^(id responseObject) {
        //获取所有城市数组
        _model.checkModel = [responseObject objectForKey:@"data"];
        [_model updateCityStationsCode];
        [_model getCity24ValueWithCityCode:[RJUserData defaultRJUserData].currentCityCode];
        if ([RJUserData defaultRJUserData].isProvince) {
            [_statusView setData:responseObject];
            [self setCityTableData:_model.checkModel];
            //设置数据（默认为成都，及数组第一个城市）
            _model.cityColor = [_model.checkModel[0] objectForKey:@"COLOR"];
            /**默认显示成都*/
            _model.cityModel =[_model.checkModel[0] objectForKey:@"STATIONTYPES"];
            
        } else {
            [_bottomView reSetCityStation:responseObject[@"data"] cityName:[RJUserData defaultRJUserData].currentCity];
            if (_model.checkModel.count == 0) {
                [self removeLoadView];
                return ;
            }
            NSDictionary * allDic = responseObject[@"data"];
            for (NSDictionary * dic in allDic) {
                NSString * citcode = [NSString stringWithFormat:@"%@",dic[@"CITYCODE"]];
                if ([citcode isEqualToString:userCityCode]) {
                    [[self getCheckSendVC] setSendData:dic];
                    NSDictionary * stationsArray = dic;
                    NSArray * dictionary = stationsArray[@"STATIONTYPES"];
                    NSDictionary * codeArray1 = dictionary[0];
                    NSArray * stations = codeArray1[@"STATIONS"];
                    for (NSDictionary * dic in stations) {
                        NSString * codeString = dic[@"STATIONCODE"];
                        [_allCityCode addObject:codeString];
                    }
                    if (!_sendModel) {
                        _sendModel = [[RJCheckSendModel alloc] init];
                        [_sendModel getAllstationCode:_allCityCode];
                        
                    }
                    _sendModel.getAllDataBlock = ^(NSMutableDictionary *data){
                        _allStationData = data;
                    };
                }
                [_bottomView setAirKey:@"aqi"];
                }
            
            }
         [self removeLoadView];
    }failBlack:^(id response) {
        [self removeLoadView];
        if (!_isNetFail) {
            _isNetFail = YES;
            [RJTools showTitle:@"网络异常" msg:@"网络异常，请点击重试！" cancelString:@"取消" confirmString:@"重试" confirmBlock:^{
                _isNetFail = NO;
                [self retryNetRequest];
            } vc:self];
        }
    }];
}

- (void)retryNetRequest
{
    [self netRequsetAllCityAndStation];
}

#pragma mark -- getTwoTopSectionView

- (void)showType
{
    [self getTwoTopSectionView];
    [self removeLoadView];
}

- (void)getTwoTopSectionView{
    _twoTopSectionView = [[UIView alloc] initWithFrame:CGRectMake(0,0, ScreenWidth, downHeight)];
    _twoTopSectionView.backgroundColor = GetRGBColor(246, 250, 251, 1);
    [_twoTopSectionView.layer setShadowColor:[UIColor grayColor].CGColor];
    [_twoTopSectionView.layer setShadowOffset:CGSizeMake(0, 0.5)];
    [_twoTopSectionView.layer setShadowOpacity:0.5];
    [self.mainView addSubview:_twoTopSectionView];
    NSInteger stationTypeCount = _bottomView.stationType.count;
    CGFloat width = ScreenWidth/stationTypeCount;
    NSArray * titleArray = _bottomView.stationType;
    for (NSUInteger i = 0; i < titleArray.count; i ++) {
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0+width*i,0, width, 30)];
        [button setTitleColor:GetRGBColor(85, 85, 85, 1) forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont systemFontOfSize:(DeviceType >= 6 ? 16 : 14)]];
        [button setTitleColor:SysMainColor forState:UIControlStateSelected];
        [button setTitle:titleArray[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(getTwoTopSectionViewBUtton:) forControlEvents:UIControlEventTouchDown];
        button.tag = i + 200;
        if (i == 0) {
            [button setTitleColor:SysMainColor forState:UIControlStateNormal];
            _currentButton = button;
        }
        [self.mainView addSubview:button];
    }
     _twoTopLine = [[UIView alloc] initWithFrame:CGRectMake(0, downHeight-3, width, 3)];
    _twoTopLine.backgroundColor = SysMainColor;
    [_twoTopSectionView addSubview:_twoTopLine];
  
}
- (void)getTwoTopSectionViewBUtton:(UIButton *)sender{
    NSUInteger tag = sender.tag - 200;
    if (_currentButton == sender) {
        return;
    }
    CGFloat originX = sender.frame.origin.x;
    CGFloat width = ScreenWidth/_bottomView.stationType.count;
   [_currentButton setTitleColor:GetRGBColor(85, 85, 85, 1) forState:UIControlStateNormal];
    [sender setTitleColor:SysMainColor forState:UIControlStateNormal];
    if (tag == 0) {
        [self updateLineWithKey:_pollutants isCityStation:YES];
        _stationType = YES;
    }else if (tag == 1){
        _stationType = NO;
        [self updateLineWithKey:_pollutants isCityStation:NO];
    }
    NSString * titleString = sender.titleLabel.text;
    [_bottomView updateBottomTable:titleString];
    [UIView animateWithDuration:0.35 animations:^{
        _twoTopLine.frame = CGRectMake(originX, downHeight -3, width, 3);
    }];
    _currentButton = sender;
}
/**获取所有城市（更新城市列表）*/
- (void)setCityTableData:(NSArray *)data
{
    NSMutableArray * citys = [[NSMutableArray alloc] init];
    for (NSDictionary * cityData in data) {
        NSString * string = [cityData objectForKey:@"CITYNAME"];
        NSRange range = [string rangeOfString:@"["];
        NSString * code = [cityData objectForKey:@"CITYCODE"];
        [citys addObject:@{code:[string substringToIndex:range.location - 1]}];
    }
    [[self getCityTable] setData:citys];
}

- (UIButton *)getExplainButton:(CGRect)frame
{
    if (!_explainButton) {
        _explainButton = [[UIButton alloc] initWithFrame:frame];
        [_explainButton setBackgroundColor:GetRGBColor(100, 100, 100, 0.5)];
        [_explainButton setTitle:@"图例" forState:UIControlStateNormal];
        _explainButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_explainButton.layer setCornerRadius:2];
        [_explainButton addTarget:self action:@selector(pressExplainButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _explainButton;
}

- (RJCheckSendVC *)getCheckSendVC
{
     NSInteger index = _sendProblemCount + _proplemCount;
    if (!_sendCheckVC) {
        [self.navBar setReturnButtonHidden:YES];
        _sendCheckVC = [[RJCheckSendVC alloc] init];
        [_sendCheckVC.view setFrame:CGRectMake(0, 0, 50, 50)];
        [self.navBar addSubview:_sendCheckVC.view];
        [self addChildViewController:_sendCheckVC];
    }
     _sendCheckVC.markCount = index;
    return _sendCheckVC;
}

- (RJStatusTable *)getStatusTable
{
    if (!_statusView) {
        _statusView = [[RJStatusTable alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - sysTabbarHeight) style:UITableViewStylePlain];
        [_statusView setDelegate:self];
    }
    return _statusView;
}

- (RJOutCityView *)getCityTable
{
    if (!_cityTable) {
        CGFloat width = 70;
        CGFloat height = 35;
        CGFloat x = ScreenWidth/2-15;
        CGFloat y = 10;
        _cityTable = [[RJOutCityView alloc] initWithFrame:CGRectMake(x, y, width, height) isShowTitle:NO];
        [_cityTable setDelegate:self];
    }
    return _cityTable;
}

/**获取折线图*/
- (RJLineView *)getLineViewWithData:(NSDictionary *)data frame:(CGRect)frame
{
    if (!_lineView) {
        frame.origin.y += downHeight;
        frame.size.height -= downHeight;
        _lineView = [[RJLineView alloc] initWithFrame:frame data:data timeArray:_timeArray];
    }
    return _lineView;
}

/**获取中部标签栏*/
- (CheckBottomSectionView *)getSectionView:(CGRect)rect
{
    if (!_sectionView) {
        rect.origin.y += 38;
        _sectionView = [[CheckBottomSectionView alloc] initWithFrame:rect];
        [_sectionView setDelegate:self];
    }
    return _sectionView;
}

- (RJHomeTopSectionView *)getTypeView:(CGRect)rect
{
    if (!_typeView) {
        rect.origin.y -= 0;
        _typeView = [[RJHomeTopSectionView alloc] initWithFrame:rect titles:@[@"AQI",@"SO₂",@"NO₂",@"CO",@"O₃",@"PM₁₀",@"PM"]];
        [_typeView setBackgroundColor:[UIColor whiteColor]];
        [_typeView setDelegate:self];
        [_typeView.layer setShadowColor:[UIColor grayColor].CGColor];
        [_typeView.layer setShadowOffset:CGSizeMake(0, 0.5)];
        [_typeView.layer setShadowOpacity:0.5];
        [_typeView setAlpha:1];
        
    }
    return _typeView;
}

- (RJCheckBottomView *)getCheckBottomView:(CGRect)rect
{
    if (!_bottomView) {
        rect.origin.y += 38;
        _bottomView = [[RJCheckBottomView alloc] initWithFrame:rect];
        [_bottomView setAirKey:@"aqi"];
        [_bottomView setDelegate:self];
        [_bottomView.layer setShadowColor:[UIColor grayColor].CGColor];
        [_bottomView.layer setShadowOffset:CGSizeMake(0, 0.5)];
        [_bottomView.layer setShadowOpacity:0.5];
    }
    return _bottomView;
}

- (RJCheckExplainView *)getExplainView:(CGRect)frame
{
    if (!_explainView) {
        frame.origin.y += downHeight;
        _explainView = [[RJCheckExplainView alloc] initWithFrame:frame];
        [_explainView setBackgroundColor:[UIColor redColor]];
    }
    return _explainView;
}

- (UIView *)getCityTableView
{
    if (!_cityTableView) {
        _cityTableView = [[UIView alloc] initWithFrame:ScreenBounds];
        [_cityTableView setBackgroundColor:[UIColor grayColor]];
        [_cityTableView setAlpha:0.3];
        UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickCityControlView)];
        [tapGesture setNumberOfTouchesRequired:1];
        [_cityTableView addGestureRecognizer:tapGesture];
    }
    return _cityTableView;
}
#pragma mark - event
- (void)pressReturnButton:(UIButton *)sender
{
    CGRect rect = CGRectMake(0, 0, -ScreenWidth, ScreenHeight - sysTabbarHeight);
    [[self getStatusTable].view setFrame:rect];;
    [self.view addSubview:[self getStatusTable].view];
    [self addChildViewController:[self getStatusTable]];
    [_statusView updateData];
    [self setStatusViewAnimWithShow:YES];
}

- (void)pressExplainButton:(UIButton *)sender
{
    [_explainView setShow:!_explainView.isShow];
}

- (void)clickCityControlView
{
    if (_cityTableView) {
        [[self getCityTable] setViewFrame:NO];
        [_cityTableView removeFromSuperview];
    }
}

#pragma mark - function
- (void)setStatusViewAnimWithShow:(BOOL)isShow
{
    CGRect rect = _statusView.view.frame;
    rect.origin.x = (isShow ? 0 : -rect.size.width);
    [UIView animateWithDuration:0.5f animations:^{
        [_statusView.view setFrame:rect];
    } completion:^(BOOL finished) {
        if (finished && !isShow) {
            [_statusView removeFromParentViewController];
            [_statusView.view removeFromSuperview];
            _statusView = nil;
        }
    }];
}

- (void)checkNetRequest
{
    if ((_lineNetRequest != NetRequestStatusDoing)
        && (_stationsNetRequest != NetRequestStatusDoing)) {
        [self removeLoadView];
    }
}

#pragma mark - sendMessageToCity
- (void)sendMessageToCity{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"是否下发!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 1000;
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 1000 && buttonIndex == 1) {
        [self sendMessageNet];
    }
}

- (void)sendMessageNet{
    NSUserDefaults *userDefailt = [NSUserDefaults standardUserDefaults];
    NSString *userName = [userDefailt objectForKey:@"userName"];
    NSDictionary * request = @{@"citycode":_cityCode,@"timepoint":[RJTools getTimeWithFormat:@"yyyy-MM-dd" time:YesterdayDate],@"status":@1,@"userName":userName,@"stationcode":_stationCodeString};
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].SendMessageToCity data:request  completeBlock:^(id responseObject) {
//        NSLog(@"%@",responseObject);
        NSString *status = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
        if ([status isEqualToString:@"-1"]) {
            [RJTools showTitle:@"失败!" msg:@"数据还未接入" cancelString:@"知道了" vc:self];
        }else if ([status isEqualToString:@"1"]){
             [RJTools showTitle:@"失败!" msg:@"数据已经下发过了,不能重复下发" cancelString:@"知道了" vc:self];
        }else if([status isEqualToString:@"0"]){
        [RJTools showTitle:@"成功!" msg:@"数据下发成功" cancelString:@"知道了" vc:self];
        }else if([status isEqualToString:@"2"]){
            [RJTools showTitle:@"失败!" msg:@"数据下发失败" cancelString:@"知道了" vc:self];
        }else if ([status isEqualToString:@"-2"]){
            [RJTools showTitle:@"失败!" msg:@"参数错误" cancelString:@"知道了" vc:self
             ];
        }
        
    } failBlack:^(id response) {
//        NSLog(@"------%@",response);
    }];
    
}
- (void)addLoadView
{
    CGRect rect = self.view.bounds;
    rect.origin.y = 50;
    rect.size.height -= 50;
    RJLoadView * loadView = [[RJLoadView alloc] initWithFrame:rect];
    [loadView setTag:400];
    [self.view addSubview:loadView];
}

- (void)removeLoadView
{
    RJLoadView * loadView = (RJLoadView *)[self.view viewWithTag:400];
    if (loadView) {
        [loadView removeSelf];
    }
}

#pragma mark - RJCityTableDelegate
- (void)didPressCityBar:(BOOL)isShow
{
    if (isShow) {
        [self.view insertSubview:[self getCityTableView] belowSubview:self.cityTable];
    } else if(_cityTableView) {
        [_cityTableView removeFromSuperview];
    }
}

#pragma mark -- OUTCityView
- (void)didSelectedRow:(NSUInteger)rowNumber data:(NSDictionary *)data
{
    if (_twoTopSectionView) {
        [_twoTopSectionView removeFromSuperview];
        _twoTopSectionView = nil;
    }
    [self addLoadView];
    _stationsNetRequest = NetRequestStatusDoing;
//    [self getTwoTopSectionView];
    _allStationCode = [NSMutableArray array];
    _cityCode = [data allKeys][0];
    [self.navBar.centerCityLabel setText:[data allValues][0]];
    [self addLoadView];
    _currentCityCount = rowNumber;
    [_bottomView reSetCityStation:[_model.checkModel[_currentCityCount] objectForKey:@"STATIONTYPES"] cityName:[data allValues][0]];
//    NSDictionary *dic = _model.cityModel[0];
//    _colorArray = dic[@"STATIONS"];
     NSArray *array = [_model.checkModel[_currentCityCount] objectForKey:@"STATIONTYPES"];
    [_model getCity24ValueWithCityCode:[_model.checkModel[_currentCityCount] objectForKey:@"CITYCODE"]];
    NSDictionary *dic = array[0];
    NSArray *arr = dic[@"STATIONS"];
    NSArray * arr1 = [NSArray array];
    if (array.count > 1) {
        NSDictionary *dic1 = array[1];
       arr1 = dic1[@"STATIONS"];
    }
    
//    for (NSDictionary * dictionNary in arr) {
//        [_allStationCode addObject:dictionNary[@"STATIONCODE"]];
//    }
//    for (NSDictionary * dictionNary1 in arr1) {
//        [_allStationCode addObject:dictionNary1[@"STATIONCODE"]];
//    }
//    for (NSInteger i = 0; i < arr.count; i ++) {
////        [_allStationCode addObject:arr[i][@"STATIONTYPEID"]];
//        [_colorArray addObject:arr[i][@"POSITIONNAME"]];
//    }
//
    for (NSInteger i = 0; i < arr.count; i ++) {
        [_allStationCode addObject:arr[i][@"STATIONCODE"]];
//        [_colorArray addObject:arr[i][@"POSITIONNAME"]];
    }
//    for (NSInteger i = 0; i < arr.count; i ++) {
//        [_allStationCode addObject:arr[i][@"STATIONCODE"]];
//        //        [_colorArray addObject:arr[i][@"POSITIONNAME"]];
//    }
    for (NSInteger i = 0; i < arr1.count; i ++) {
        [_allStationCode addObject:arr1[i][@"STATIONCODE"]];
        //        [_colorArray addObject:arr[i][@"POSITIONNAME"]];
    }
    _stationCodeString = [_allStationCode componentsJoinedByString:@","];
}

#pragma mark - CheckBottomButton
- (void)checkBottomSection:(CheckBottomSectionView *)view didSelect:(NSUInteger)count
{
    CGRect rect = _typeView.frame;
    rect.origin.y += (_isSelectAnim ? -40 : 40);
    _isSelectAnim = !_isSelectAnim;
    [UIView animateWithDuration:0.2 animations:^{
        CGFloat alpha = _typeView.alpha;
        alpha = (alpha == 0 ? 1 : 0);
        [_typeView setAlpha:alpha];
        [_typeView setFrame:rect];
    }];
//    NSArray * airs = @[@"AQI",@"PM2.5",@"PM10",@"O3",@"SO2",@"NO2",@"CO"];
//    NSArray * airs2 = @[@"aqi",@"so2",@"no2",@"co",@"o3",@"pm10",@"pm2_5"];
    
}

#pragma mark - RJHomeTypeDelegate
- (BOOL)HomeTopSectionView:(RJHomeTopSectionView *)sectionView didSelectCount:(NSUInteger)count isLeft:(BOOL)isLeft
{
//    NSArray * airs = @[@"AQI",@"PM₂.₅",@"PM₁₀",@"O₃", @"SO₂",@"NO₂",@"CO"];
    NSArray * airs = @[@"AQI",@"SO₂",@"NO₂",@"CO",@"O₃",@"PM₁₀",@"PM₂.₅"];
    NSArray * airs2 = @[@"aqi",@"so2",@"no2",@"co",@"o3",@"pm10",@"pm2_5"];
//    NSArray * airs2 = @[@"aqi",@"pm2_5",@"pm10",@"o3",@"so2",@"no2",@"co"];
    [_bottomView setAirKey:airs2[count]];
    _pollutants = airs[count];
    [self updateLineWithKey:airs[count] isCityStation:_stationType];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"airName" object:airs[count]];
    return YES;
}

#pragma mark - RJCheckDataVCDelegate
-(void)didSelectedRow:(NSUInteger)row data:(NSDictionary *)data position:(NSString *)position modol:(NSArray *)model
{
    NSString * stationCode = data[@"STATIONCODE"];
    RJCheckDataVC * checkDataVC = [[RJCheckDataVC alloc] initWithData:@{@"stationCode":stationCode} title:position data:model selectRow:row];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proplemData:) name:@"CheckProplemCount" object:nil];
    checkDataVC.leftModel = model;
    [self.navigationController pushViewController:checkDataVC animated:YES];
}

#pragma mark -- 有疑问的数据
/**有疑问的数据*/
- (void)proplemData:(NSNotification *)notification{
    NSString * string = notification.object;
    self.proplemCount = [string integerValue];
}

- (void)sendCheckProplemData:(NSNotification *)notification{
    NSString *string = notification.object;
    self.sendProblemCount = [string integerValue];
}
#pragma mark - RJCheckBottomViewDelegate
/**获取到数据并刷新数据*/
- (void)updateDownWithData:(NSDictionary *)data
{
    if (data[@"result"]) {
        _stationsNetRequest = NetRequestStatusSucceed;
    } else {
        _stationsNetRequest = NetRequestStatusFailure;
    }
    [self checkNetRequest];
}

- (void)netRequestBottomFail
{
    if (!_isNetFail) {
        _isNetFail = YES;
        [RJTools showTitle:@"网络异常" msg:@"网络异常，请点击重试！" cancelString:@"取消" confirmString:@"重试" confirmBlock:^{
            _model.cityModel =[_model.checkModel[_currentCityCount] objectForKey:@"STATIONTYPES"];
            if (![RJUserData defaultRJUserData].isProvince) {
                [_bottomView reSetCityStation:_model.checkModel cityName:nil];
            } else {
                [_bottomView reSetCityStation:_model.cityModel cityName:nil];
            }
            [_model getCity24ValueWithCityCode:[_model.checkModel[_currentCityCount] objectForKey:@"CITYCODE"]];
            _isNetFail = NO;
            
        } vc:self];
    }
}

#pragma mark - RJStatusTableCellDelegate
- (void)RJStatusTable:(RJStatusTable *)table rowNum:(NSInteger)rowNum cityCode:(NSNumber *)code
{
    _cityCode = code;
    _currentCityCount = rowNum;
    [_bottomView removeFromSuperview];
    _bottomView = nil;
    [self addLoadView];
    _stationsNetRequest = NetRequestStatusDoing;
    for (UIView * view in [self.mainView subviews]) {
        [view removeFromSuperview];
    }
    
//    [_twoTopSectionView removeFromSuperview];
//    [_twoTopLine removeFromSuperview];
//    _twoTopSectionView = nil;
//    _twoTopLine = nil;
    //选取器
    CGRect typeRect = CGRectMake(0, CGRectGetHeight(self.mainView.frame) / 2, ScreenWidth , 40);
    [self.mainView addSubview:[self getTypeView:typeRect]];
    
    //类型
    CGRect sectionRect = CGRectMake(0, CGRectGetHeight(self.mainView.frame) / 2, ScreenWidth , 40);
    [self.mainView addSubview:[self getSectionView:sectionRect]];
    
    //列表
    CGFloat _typeMaxY = CGRectGetMaxY(_typeView.frame) + 5;
    CGRect bottomRect = CGRectMake(0, _typeMaxY, ScreenWidth, CGRectGetHeight(self.mainView.frame) - _typeMaxY - 5);
    [self.mainView insertSubview:[self getCheckBottomView:bottomRect] belowSubview:_typeView];
    //折线图
    CGRect lineRect = CGRectMake(0, 0, ScreenWidth, CGRectGetHeight(self.mainView.frame) / 2 - 5);
    [self.mainView addSubview:[self getLineViewWithData:nil frame:lineRect]];

    //图例按钮
    CGRect rect = CGRectMake(0, lineRect.origin.y + lineRect.size.height - 40, 40, 40);
    [self.view addSubview:[self getExplainButton:rect]];
    
    //图例
    CGFloat explainY = sectionRect.origin.y;
    CGRect explainRect = CGRectMake(-ScreenWidth,
                                    explainY,
                                    ScreenWidth,
                                    ScreenHeight - sysTabbarHeight - explainY);
    [self.mainView addSubview:[self getExplainView:explainRect]];

    [self setStatusViewAnimWithShow:NO];
    if (rowNum != -1) {
        [_cityTable simulationPressCityWithRow:rowNum];
    }
}

- (void)netRequsetFail
{
    [RJTools showTitle:@"网络异常" msg:@"网络异常，请点击重试！" cancelString:@"取消" confirmString:@"重试" confirmBlock:^{
        [_statusView updateData];
    } vc:self];
}

#pragma mark - RJMainSuperDelegate
- (void)RJMainSuperVCFreeAll
{
    _isRun = NO;
    [_bottomView freeFunc];
}

#pragma mark - system
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_cityTable setViewFrame:NO];
}

#pragma mark - system
- (void)didGetCity24Value:(NSNotification *)data
{
    NSDictionary * dic = data.object;
    _pollutants = @"AQI";
    _stationType = YES;
    if (dic[@"result"]) {
        _lineNetRequest = NetRequestStatusSucceed;
        [self updateLineWithKey:@"AQI" isCityStation:YES];
    } else {
        _lineNetRequest = NetRequestStatusFailure;
        if (!_isNetFail) {
            _isNetFail = YES;
            [RJTools showTitle:@"网络异常" msg:@"网络异常，请点击重试！" cancelString:@"取消" confirmString:@"重试" confirmBlock:^{
                [_model getCity24ValueWithCityCode:[RJUserData defaultRJUserData].currentCityCode];
                _isNetFail = NO;
            } vc:self];
        }
    }
    [self checkNetRequest];
}

- (void)updateLineWithKey:(NSString *)key isCityStation:(BOOL)isCityStation
{
    if (!_isRun) {
        return;
    }
    if (_myBlock) {
        self.myBlock(isCityStation);
    }
    //更新折线图
    if (_lineView) {
        [_lineView removeFromSuperview];
        _lineView = nil;
    }
    NSArray * array = [NSArray array];
    NSArray * airs = @[@"AQI",@"PM₂.₅",@"PM₁₀",@"O₃", @"SO₂",@"NO₂",@"CO"];
    NSInteger count = [airs indexOfObject:key];
//    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:airs];
    NSArray * airsTitle = @[@"AQI",@"PM2.5",@"PM10",@"O3",@"SO2",@"NO2",@"CO"];
    NSString *keyString = airsTitle[count];
    if (isCityStation) {
        array = _model.city24Dic[keyString];
    }else if (!isCityStation){
        array = _model.country24Dic[keyString];
    }
    _timeArray = _model.timeArray;
    if (array) {
        NSMutableArray * keyArr = [NSMutableArray array];
        for (NSDictionary * dic in array) {
            NSString * key = [[dic allKeys] firstObject];
            [keyArr addObject:key];
        }
        NSArray * sortedKeyArr = [keyArr sortedArrayUsingSelector:@selector(compare:)];
        NSMutableArray * sortArr = [NSMutableArray array];
        for (NSString * key in sortedKeyArr) {
            for (NSDictionary * dic in array) {
                NSString * stationKey = [[dic allKeys] firstObject];
                if ([stationKey isEqualToString:key]) {
                    [sortArr addObject:dic];
                }
            }
        }
        CGRect lineRect = CGRectMake(0, 0, ScreenWidth, CGRectGetHeight(self.mainView.frame) / 2 - 5);
        [self.mainView addSubview:[self getLineViewWithData:@{key:sortArr} frame:lineRect]];
        if (isCityStation) {
             [_explainView setStationNames:_model.cityStationsName];
        }else if (!isCityStation){
            [_explainView setStationNames:_model.countryStationsName];
        }
    }
}
@end
